package com.cspg.design.presenter;

import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import com.cspg.design.CSPGApplication;
import com.cspg.design.CheckPermissionsActivity;
import com.cspg.design.MainActivity;
import com.cspg.design.R;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.commonBean.CommonBean;
import com.cspg.design.bean.userInfoBean.UserInfoBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dto.RoleDto;
import com.cspg.design.model.User;
import com.cspg.design.model.UserModel;
import com.cspg.design.request.Login;
import com.cspg.design.ui.login.LoginActivity;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.CSPGProgressBar;
import com.cspg.design.widget.ToastUtils;

import org.greenrobot.greendao.rx.RxDao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;

public class LoginPresenter implements IPresenter{

    private final Login loginModel;
    private final AppCompatActivity activity;

    private CSPGProgressBar cspgProgressBar;
    private RxDao<UserInfoBean, Long> userInfoBeanLongRxDao;

    public LoginPresenter(CheckPermissionsActivity activity) {
        this.loginModel = new Login(this);
        this.activity = activity;
    }

    public LoginPresenter(AppCompatActivity activity) {
        this.loginModel = new Login(this);
        this.activity = activity;
    }


    public void login(final  String username, final  String pwd)  {
//        activity.showProgress();
        if(cspgProgressBar == null)
        {
            cspgProgressBar = CSPGProgressBar.show(activity);
        }else {
            cspgProgressBar.show();
        }
        try {

            loginModel.loginNoCode( username,  pwd);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void upatePassword(final  String oldPass, final  String newPass)  {
        if(cspgProgressBar == null)
        {
            cspgProgressBar = CSPGProgressBar.show(activity);
        }else {
            cspgProgressBar.show();
        }
        try {

            loginModel.updatePassword( oldPass,  newPass);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }



    public void getLoginFailure(String msg) {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, msg);
    }

    public void updateSuccess(String msg)
    {
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, msg);
    }

    @Override
    public void netWorkError(String netError) {
//        activity.hideProgress();
//        activity.toast(netError);

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, netError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestFailure(String noDataError) {
//        activity.hideProgress();
////        activity.toast(noDataError);
        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        ToastUtils.toast(activity, noDataError);
        if (activity instanceof MainActivity) {
            //activity.openNewActivity(LoginActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }
    }

    @Override
    public void httpRequestSuccess() {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        if (activity instanceof LoginActivity) {
            LoginActivity loginActivity = (LoginActivity) activity;
            loginActivity.openNewActivity(MainActivity.class);
            addLocalData();
        } else {
//            activity.openNewActivity(MainActivity.class);
            Intent intent = new Intent();
            intent.setClass(activity, LoginActivity.class);
            activity.startActivity(intent);
        }

    }

    public void loginSuccess(UserModel userModel)
    {

        if (null != cspgProgressBar && cspgProgressBar.isShowing()) {
            cspgProgressBar.dismiss();
        }
        if (activity instanceof LoginActivity) {
//            LoginActivity loginActivity = (LoginActivity) activity;
//            loginActivity.openNewActivity(MainActivity.class);

        UserInfo userInfo = UserInfo.getInstance();
        List<RoleDto> roleDto = userModel.getUser().getUser().getRoles();
        if (roleDto.size()> 1)
        {
                int countRole= 0;
                List<String> rols = new ArrayList<>();
                for (int i = 0;i< roleDto.size();i++)
                {
                    rols.add(roleDto.get(i).getName());
                    countRole++;
                }
                if (countRole == 0)
                {
                    UserInfo.setUserInfo(userInfo);
                    addLocalData();
                }
                else
                {
                    new AlertListDialog.ListBuilder(this.activity)
                            .setDividerColorRes(R.color.color_divider)
                            .setDividerHeightRes(R.dimen.dp1)
                            .setTitle("请选择你的工作岗位")
                            .setIcon(R.drawable.ic_info)
                            .setCancelable(false)
                            .setItems(rols.toArray(new String[rols.size()]), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    userInfo.role = rols.get(which);
                                    UserInfo.setUserInfo(userInfo);
                                    addLocalData();
                                }
                            }).create().show();
                }
        }
        else
        {
          String role =  userModel.getUser().getUser().getRoles().get(0).getName();
          userInfo.role = role;
          UserInfo.setUserInfo(userInfo);
          addLocalData();

        }

        }

    }

    private void addLocalData(){
        DaoSession daoSession = ((CSPGApplication) activity.getApplication()).getDaoSession();
        userInfoBeanLongRxDao = daoSession.getUserInfoBeanDao().rx();
        UserInfo userInfo = UserInfo.getInstance();
        UserInfoBean userInfoBean = new UserInfoBean( );
        userInfoBean.setLogon("Y");
        userInfoBean.setDate(new Date());
        userInfoBean.setUserName(userInfo.userName);
        userInfoBean.setPassword(userInfo.password);
        userInfoBean.setToken(userInfo.token);
        userInfoBean.setRole(userInfo.role);
        userInfoBean.setUnit(userInfo.unit);
        daoSession.getUserInfoBeanDao().deleteAll();
        List<UserInfoBean> list = daoSession.getUserInfoBeanDao().queryBuilder().list();
        userInfoBeanLongRxDao.insertOrReplace(userInfoBean)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(userInfoBean1 -> {
                    Log.e(activity.getClass().getName(), userInfoBean1.getUserName());
                    Log.e(activity.getClass().getName(), userInfoBean1.getToken());
                    activity.startActivity(new Intent(activity,MainActivity.class));
                });
    }
}